package logic

import (
	"cart_srv/cart"
	"context"
	"fmt"
	"shop_srv/goods"
	"strconv"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddCartLogic) AddCart(req *types.AddCartRequest) (resp *types.Response, err error) {
	//商品是否存在
	goodsId, err := l.svcCtx.GoodsSrv.GetGoodsByGoodsId(l.ctx, &goods.GetGoodsByGoodsIdRequest{GoodsId: req.GoodsId})
	if err != nil {
		return &types.Response{
			Code:    -1,
			Message: "服务器内部错误",
			Data:    nil,
		}, nil
	}
	if goodsId.GoodsId == 0 {
		return &types.Response{
			Code:    -2,
			Message: "商品不存在",
			Data:    nil,
		}, nil
	}
	//库存是否充足
	stock, err := l.svcCtx.GoodsSrv.GetGoodsStock(l.ctx, &goods.GetGoodsStockRequest{GoodsId: req.GoodsId})
	if err != nil {
		return &types.Response{
			Code:    -3,
			Message: "服务器内部错误",
			Data:    nil,
		}, nil
	}
	if stock.GoodsStatus > req.Num {
		return &types.Response{
			Code:    -4,
			Message: "商品库存不足",
			Data:    nil,
		}, nil
	}
	//虚拟库存
	//购物车中是否存在该商品
	userId := l.ctx.Value("userId").(string)
	uid, _ := strconv.Atoi(userId)
	fmt.Println(uid)
	response, err := l.svcCtx.CartSrv.ExistCartGoods(l.ctx, &cart.ExistCartGoodsRequest{
		UserId:  int64(uid),
		GoodsId: req.GoodsId,
	})
	if err != nil {
		return &types.Response{
			Code:    -5,
			Message: "服务器内部错误",
			Data:    nil,
		}, nil
	}
	//if 存在数量累加
	if response.Exist {
		_, err := l.svcCtx.CartSrv.UpdateCart(l.ctx, &cart.UpdateCartRequest{
			UserId:  int64(uid),
			GoodsId: req.GoodsId,
			Num:     req.Num,
		})
		if err != nil {
			return &types.Response{
				Code:    -6,
				Message: "服务器内部错误",
				Data:    nil,
			}, nil
		}
	} else { //不存在就添加
		_, err := l.svcCtx.CartSrv.AddCart(l.ctx, &cart.AddCartRequest{
			UserId:     int64(uid),
			GoodsId:    req.GoodsId,
			GoodsTitle: goodsId.GoodsTitle,
			GoodsPrice: goodsId.GoodsPrice * 100,
			Num:        req.Num,
		})
		if err != nil {
			return &types.Response{
				Code:    -7,
				Message: "服务器内部错误",
				Data:    nil,
			}, nil
		}
	}
	return &types.Response{
		Code:    0,
		Message: "购物车添加成功",
		Data:    nil,
	}, nil
}
